\documentclass[10pt]{article}
\usepackage[margin=1in]{geometry}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{url}
\usepackage{framed, color}
\definecolor{shadecolor}{rgb}{1,1,1}
\usepackage{graphicx}
\usepackage{listings}
\usepackage{color}
\usepackage{listings}
\lstset{ %
language=R,                % choose the language of the code
basicstyle=\footnotesize,       % the size of the fonts that are used for the code
numbers=left,                   % where to put the line-numbers
numberstyle=\footnotesize,      % the size of the fonts that are used for the line-numbers
stepnumber=1,                   % the step between two line-numbers. If it is 1 each line will be numbered
numbersep=7pt,                  % how far the line-numbers are from the code
backgroundcolor=\color{white},  % choose the background color. You must add \usepackage{color}
showspaces=false,               % show spaces adding particular underscores
showstringspaces=false,         % underline spaces within strings
showtabs=false,                 % show tabs within strings adding particular underscores
frame=single,           % adds a frame around the code
tabsize=2,          % sets default tabsize to 2 spaces
captionpos=b,           % sets the caption-position to bottom
breaklines=true,        % sets automatic line breaking
breakatwhitespace=false,    % sets if automatic breaks should only happen at whitespace
escapeinside={\%*}{*)},          % if you want to add a comment within your code
xleftmargin=.5in,
xrightmargin=.25in
}

\title{Week 1: Basic R}
\author{Phong Le, Raquel G. Alhama, Willem Zuidema}

\begin{document}
\lstset{language=R}
\renewcommand{\lstlistingname}{Code}

\maketitle

We will use R in all of our computer labs, that's why the first week is dedicated
to the most important and difficult task in the course: making friends with R. 
If you are absolutely new to R, we strongly recommend you follow this 
tutorial first
\begin{itemize}
    \item \url{http://cran.r-project.org/doc/contrib/Marthews-BeginnersRcourse.zip}
\end{itemize}
Ready? Then, say hello to R by typing \texttt{print("Hello R!")}. 


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Vector and Matrix}
\label{section vector and matrix}

\subsection{Construction}

There are many ways to construct a vector. The first, also the simplest, way is
to use the \texttt{c} function, e.g., \texttt{vec <- c(1,2,3)} creates a 
\textit{column} vector 
\[
    vec = \begin{pmatrix} 
            1 \\
            2 \\
            3 
        \end{pmatrix}
\]
Another way is to use the \texttt{rep}, \texttt{seq}, and
\texttt{runif} functions etc.
(Check yourself what those functions do by typing \texttt{help(function\_name)}.)

\begin{framed}
Exercise \ref{section vector and matrix}.1: Create the following vectors
\[
    a = \begin{pmatrix} 
            1.5 \\
            -1 \\
            3 
        \end{pmatrix} \;\;
    b = \begin{pmatrix} 
            -1 \\
            -1 \\
            -1
        \end{pmatrix} \;\;
    c = \begin{pmatrix} 
            2 \\
            4 \\
            6 \\
            ... \\
            24
        \end{pmatrix} \;\;
\]
and vector \texttt{d} containing 12 real numbers drawn from the uniform distribution 
\texttt{U(-1,1)}. (Hint: use \texttt{rep, seq, runif} to construct \texttt{b, c, d}
respectively.)
\end{framed}

To create a matrix, we use 
\begin{center}
\texttt{matrix(vector, number\_of\_rows, number\_of\_columns)}
\end{center}
For instance, the output of \texttt{matrix(c(1,2,3,4,5,6),2,3)} is the matrix
\[
    \begin{pmatrix}
        1 & 3 & 5 \\
        2 & 4 & 6
    \end{pmatrix}
\]
(Mind the element order in the matrix w.r.t. the order in the given vector.)

\begin{framed}
Exercise \ref{section vector and matrix}.2: Create the following matrices 
\begin{itemize}
    \item \[
    A = \begin{pmatrix}
            3 & 1 & 2 \\
            -4 & 2 & 0
        \end{pmatrix} \;\;
    B = \begin{pmatrix}
            1 & 2 \\
            5 & -3 \\
            -4 & 1
        \end{pmatrix}
    \]
    Type \texttt{dim(A)} to confirm that A is a $2\times3$ matrix.

    \item \texttt{C} is a $3\times3$ magic square matrix.

    \item \texttt{D} is a $3\times5$ matrix which the elements are drawn from 
    a uniform distribution. 

    \item \texttt{E} is a $5\times5$ identity matrix 
    (Hint: use the \texttt{diag} function).
\end{itemize}
\end{framed}

\subsection{Operations}
\begin{framed}
Exercise \ref{section vector and matrix}.3: Given vectors and matrices in the above exercises, 
\begin{itemize}
    \item What do you get with \texttt{a + b}, \texttt{a - b}, \texttt{a * b},
    \texttt{a / b}?
    
    \item What do you get with \texttt{a > b}, \texttt{a < b}, \texttt{a == b},
    \texttt{a != b}?

    \item Confirm that \texttt{t(B)} transposes matrix \textit{B}, assign the
    result to \texttt{Bt}. 
    
    \item What do you get with \texttt{A * B}, \texttt{A \%*\% B}, \texttt{A * Bt}, 
    \texttt{A / Bt}? What can you conclude about these operators 
    \texttt{+,-,*,\%*\%}? (especially the difference between \texttt{*} and
    \texttt{\%*\%}.)
    
    \item Confirm that \texttt{E} is an identity matrix by using matrix \texttt{D} 
    (Hint: remember that $A \times I = A$ where \texttt{I} is an identity matrix 
    and \texttt{A} is an arbitrary matrix.)
    
    \item Confirm that \texttt{solve(C)} computes the inverse of \texttt{C}. (Hint: 
    $A \times A^{-1} = A^{-1} \times A = I$ for any invertible matrix $A$.)
    
\end{itemize}
\end{framed}

\subsection{Indexing}
We can get an element by using the operator \texttt{[]}. For instance, 
\texttt{vec[i]} points to the i-th element of a vector \texttt{vec}, 
\texttt{mat[i,j]} points to the element on the i-th row, the j-th column 
of a matrix \texttt{mat}.

The operator \texttt{[]} can do further than that: we can get a set of elements.
For instance, \texttt{a[c(1,3)]} and \texttt{a[c(TRUE,FALSE,TRUE)]} 
point to the first and the third elements of vector \texttt{a};
\texttt{A[1,c(2,3)]} and \texttt{A[1,c(FALSE,TRUE,TRUE)]} point to the second 
and the third elements on the first row of matrix \texttt{A}, 
and \texttt{A[,2]} points to the second column.
(Check those yourself with \texttt{a} and \texttt{A} given above.)

\begin{framed}
Exercise \ref{section vector and matrix}.4: 
\begin{itemize}
    \item Use the operator \texttt{[]} to confirm that \texttt{C} is a magic square. 
    (Hint: use \texttt{sum} to compute the sum of all elements of a vector.)
    
    \item Find all positive elements in \texttt{a}. (Hint: use \texttt{a > 0}.)
    
    \item Find the sum of the all negative elements in \texttt{B}.
\end{itemize}
\end{framed}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Graphics}
\label{section graphics}

\paragraph{Line plot}
In order to draw a function $y=f(x)$, we can use \texttt{plot(x,y,type='l')} where
\texttt{x} is a vector containing $n$ ordered values of $x$ and \texttt{y} is a
vector such that \texttt{y[i] = f(x[i])}. For instance, the following code will draw
the function $y=sin(x)$
\begin{lstlisting}
x <- seq(-5,5,by=0.1)           # create x = (-5,-4.9,-4.8,...,4.9,5)
y <- sin(x)                     # compute y values
plot(x,y,type='l',col='blue')   # draw the graph, using blue color
savePlot("sin.png",type="png")	# save the current plot to a png file
\end{lstlisting}
If you want to draw another function on the same graph, you need to use 
the \texttt{lines} function. For instance, insert \texttt{lines(x,cos(x))}
before the last line. Now, you should get a graph similar to 
Figure~\ref{fig sin cos}.
\begin{figure}[h!]
    \centering
    \includegraphics[width=0.5\textwidth]{sin.png}
    \caption{Drawing two functions, $y=sin(x)$ and $y=cos(x)$ in one graph.}
    \label{fig sin cos}
\end{figure}


\paragraph{Scatter plot}
Remove \texttt{type='l'} and replace \texttt{lines(x,cos(x))} by
\texttt{points(x,cos(x))}, what do you get?

\paragraph{Histogram}
The \texttt{hist(u,breaks=n,...)} function draws a $n$-bin histogram of the set of values
stored in the vector \texttt{u}. For instance, the following code is to draw a 
100-bin \textit{frequency} histogram of 10 millions values drawn from the uniform
distribution $U(-1,1)$
\begin{lstlisting}
u <- runif(10000000)    # sample
hist(u,breaks=100)      # draw a 100-bin histogram of u
\end{lstlisting}

\begin{framed}
Exercise \ref{section graphics}.1: Replace \texttt{hist(u,breaks=100)} by 
\texttt{hist(u,breaks=100,probability=TRUE)}. What is the role of 
\texttt{probability=TRUE}?
\end{framed}

\begin{framed}
Exercise \ref{section graphics}.2: Confirm that the \texttt{rnorm} function 
draws samples from the normal distribution. (Hint: draw a 
\textit{probability} histogram of a large enough sample given by \texttt{rnorm}, 
and the density function of the normal distribution.)
\end{framed}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Control Structures}
\label{section control structures}

\subsection{Conditional Execution}
Think about what would happen if our languages lack the words `if', `else', 
`otherwise', etc.  and you will see why any programming language has to have 
conditional execution. In R, conditional execution is given by the following 
structure
\begin{lstlisting}
if (condition) {
    statement
} else {
    alternative
}
\end{lstlisting}
The \textit{condition} is a logical expression which may contain one of the following
operations
\begin{itemize}
    \item $x == y$ ``$x$ is equal to $y$''
    \item $x != y$ ``$x$ is not equal to $y$''
    \item $x > y$ ``$x$ is greater than $y$''
    \item $x < y$ ``$x$ is less than $y$''
    \item $x <= y$ ``$x$ is less than or equal to $y$''
    \item $x >= y$ ``$x$ is greater than or equal to $y$''
\end{itemize}
or a combination of those using the \& or \&\& operators for AND, $|$ or $||$ are the 
operators for OR.

For instance, the following code will let us know, when we flip two fair coins, whether 
the results are both `head'
\begin{lstlisting}
x <- runif(2)   # flip two fair coins
print(x)
# suppose that "> 0.5" means "head"
# we check if BOTH two values > 0.5 or not
if (x[1] > 0.5 && x[2] > 0.5) {
    # both > 0.5
    print("bingo!!!")
} else {  
    # at least one of them <= 0.5
    print("boooo!!!")
}
\end{lstlisting}
(Note: the ``else'' part is not necessary, you can omit it freely if you have nothing 
to do with it.)

\begin{framed}
Exercise \ref{section control structures}.1: Modify the code above to check whether 
at least one result is `head'.
\end{framed}

\subsection{Loops}
Suppose that we have a fair coin, and we flip it 1000 times and count how many times
the coin turns head. To do that, we use the \texttt{for} statement like this way:
\begin{lstlisting}[caption=Using the \texttt{for} loop to count how many times 
a fain coin turns head., label=code for]
x <- runif(1000)   # flip a fair coin 1000 times
count <- 0
# suppose that "> 0.5" means "head"
# note that 1:1000 creates an array (1,2,3,...,1000)
for (i in 1:1000) {
    if (x[i] > 0.5) {
        count <- count + 1
    }
}
print(count)
\end{lstlisting}
The \texttt{for} loop above iterates each element in the array (1,2,...,1000). 
Firstly, the first element is assigned to $i$, and hence we check the value $x[1]$: if 
$x[1] > 0.5$ then we increase the $count$ by 1. Then, the second element is 
assigned to $i$, and hence we check the value $x[2]$. 
And so on until the last element is assigned to $i$, and hence we check the value $x[10000]$.

Now, we want to flip the coin until it turns head. We can't use the \texttt{for} statement
because we don't know how many times we need to flip the coin. Here, we need another loop 
statement, namely \texttt{while}:
\begin{lstlisting}
while (condition) {
    statement
}
\end{lstlisting}
The \texttt{while} loop will execute the \texttt{statement} as long as the 
\texttt{condition} is correct (i.e., \texttt{TRUE}). Therefore, our problem 
is solved by the following code
\begin{lstlisting}
# suppose that "> 0.5" means "head"
x <- runif(1)   # flip the coin
print(x)
while (x <= 0.5) {
    x <- runif(1)   # flip the coin
    print(x)
}
print("bingo!!!")
\end{lstlisting}

\begin{framed}
Exercise \ref{section control structures}.2: 
\begin{itemize}
    \item Interpret the code above in your own words.
    \item Modify the code above using \texttt{repeat} (another loop statement).
\end{itemize}
\end{framed}

\paragraph{Loops are \textit{expensive} and we should avoid using them whenever we can!!!}
In order to see that, let's run the following code, which measures the execution time 
of two methods computing the sum of the all elements of a vector
\begin{lstlisting}
n <- 1000000
x <- runif(n)   # create an n-element vector
sum <- 0
    
# the first method: using for loop
ptm <- proc.time()          # start clock
for (i in 1:n) {
    sum <- sum + x[i]
}
print(sum)
print(proc.time() - ptm)    # stop clock

# the second method: using the built-in function sum()
ptm <- proc.time()
print(sum(x))
print(proc.time() - ptm)
\end{lstlisting}
You should get an output like this (note that the numbers you get should be slightly 
different due to the sampling process as well as your computer power)
\indent \begin{lstlisting}
[1] 500109.2
    user  system elapsed 
    1.308   0.000   1.311 
[1] 500109.2
    user  system elapsed 
    0.004   0.000   0.003 
\end{lstlisting}
which tells us that the two methods return the same result but with very different
execution time: the second clearly run much much (327 times) faster than the other.

\begin{framed}
Exercise \ref{section control structures}.3: How can you avoid using the \texttt{for}
loop in Code~\ref{code for}? Implement your idea. (Hint: use \texttt{x > 0.5}.)
\end{framed}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Functions}
\label{section functions}
What makes Lego bricks much more interesting than traditional toys? That is we 
can build our own toys from small pieces, and that ``The only limit is our 
imagination''. It turns out that programming also has the same principle: we
encompass our small frequently-used codes in functions (Lego bricks) in order to
build big programs (toys) faster and more robustly. 

The structure of a function is given as follows
\begin{lstlisting}
func_name <- function(arg1, arg2, ...) {
    statement
    return(output)
}
\end{lstlisting}
where \texttt{func\_name} is the function's name; \texttt{arg1}, \texttt{arg2}, etc. 
are the function's arguments (i.e., function's inputs); and \texttt{return(output)}
is to claim that the output of the function is the object \texttt{output}, which 
need to be declared in the body of the function (i.e., \texttt{statement}). 

For instance, we can wrap Code~\ref{code for} into a function like this
\begin{lstlisting}
# function count_head
# input: num_of_flips is a number of times we flip the coin
# output: the number of times the coin turns head
count_head <- function(num_of_flips) {
    x <- runif(num_of_flips)   # flip a fair coin 
    count <- 0
    for (i in 1:num_of_flips) {
        if (x[i] > 0.5) {
            count <- count + 1
        }
    }
    return(count)
}
\end{lstlisting}
Now, to flip a fair coin 10000 times and count how many times it turns head, 
we simply execute \texttt{count <- count\_head(10000)} (instead of typing 
Code~\ref{code for} again and again each time we need to perform the task).

\begin{framed}
Exercise \ref{section functions}.1: Wrap your code in Exercise 
\ref{section control structures}.3 in a function.
\end{framed}

\begin{framed}
Exercise \ref{section functions}.2 (***): Wrap your code in Exercise 
\ref{section graphics}.2 in a function such that we can do the same thing
with any sampling function and any density function. (Hint: an input to
a function can be a function.)
\end{framed}

\paragraph{Variable Scope} You are strongly recommended to understand variable
scope in R, which is presented at 
\url{http://cran.r-project.org/doc/manuals/R-intro.html\#Scope}.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Scripts}
\label{section scripts}
Programming directly in an R console is a very very bad idea because we can't 
bring our programs to another computer. Therefore, we should store our source code 
in a file and execute it anytime we want by the function \texttt{source("file\_path")}.

\begin{framed}
Exercise \ref{section scripts}.1 (!): Store your code in Exercise \ref{section functions}.1 
in a file ``coin.r'' and execute it by typing \texttt{source("coin.r")} in an R console.
(If the error ``can not open file'' occurs, you should copy the file coin.r to
the working directory, which can be queried by \texttt{getwd()}.)
\end{framed}

\section{Practical issues}
\subsection{What should you do when you get stuck?}
\paragraph{Google your problem!} R is widely used, and its user community is very large.
Therefore, you can easily find someone that had the same problem and successfully
solved it. For instance,
\begin{figure}[h!]
    \centering
    \includegraphics[width=0.8\textwidth]{can_not_open_file.png}
\end{figure}
\begin{figure}[h!]
    \centering
    \includegraphics[width=0.8\textwidth]{sum.png}
\end{figure}

If you can't find any solution on the Internet, posting your problem on the course 
forum.

\subsection{Submission}
You have to submit two files, one named `your\_name.pdf' for those exercises 
requiring explanations and math solutions, the other named `your\_name.R' with the following format
\begin{lstlisting}
# your name, your student id

print("exercise 1.1")
# your code of ex 1.1

print("exercise 1.2")
# your code of ex 1.2

...

\end{lstlisting}

Note that exercises marked with (***) are very challenging, just do them
if you have time. Those marked with (!) do not need to be submitted. 
The deadline is xx:yy:zz A/B/C.

\end{document}
